package com.ikas.ai.server.module.morningpaper.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikas.ai.server.module.morningpaper.dao.FailureRecordDao;
import com.ikas.ai.server.module.morningpaper.model.dto.FailureRecord;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: wang.qining
 * @date: 2024/2/2 9:58
 */
@Service
public class FailureRecordService extends ServiceImpl<FailureRecordDao, FailureRecord> {
    @Autowired
    private FailureRecordDao dao;

    public FailureRecord add(FailureRecord failureRecord) {
        save(failureRecord);
        return failureRecord;
    }

    public List<Integer> getYears() {
        QueryWrapper<FailureRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("failure_date").last("limit 1");
        FailureRecord failureRecord = dao.selectOne(queryWrapper);
        if (failureRecord == null) {
            return null;
        }
        String failureDate = failureRecord.getFailureDate();
        Date date = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            date = format.parse(failureDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int y = c.get(Calendar.YEAR);
        int currentYear = Calendar.getInstance().get(Calendar.YEAR);
        List<Integer> result = new ArrayList<>();
        while (y <= currentYear) {
            result.add(y++);
        }
        return result;
    }

    public Map<String, Long> statistics(Integer year) {
        QueryWrapper<FailureRecord> queryWrapper = new QueryWrapper<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        queryWrapper.between("failure_date", format.format(getMinTime(year)), format.format(getMaxTime(year)));
        queryWrapper.groupBy("failure_fw").select("failure_fw", "count(1) as count");
        List<Map<String, Object>> resultList = dao.selectMaps(queryWrapper);
        Map<String, Long> result = new HashMap<>();
        for (Map<String, Object> map : resultList) {
            String fieldValue = (String) map.get("failure_fw");
            Long count = ((Long) map.get("count"));
            result.put(fieldValue, count);
        }
        return result;
    }

    private Date getMinTime(int year) {
        // 获取最小时间（年初）
        Calendar minTime = Calendar.getInstance();
        minTime.set(Calendar.YEAR, year);
        minTime.set(Calendar.MONTH, 0);
        minTime.set(Calendar.DAY_OF_MONTH, 1);
        minTime.set(Calendar.HOUR_OF_DAY, 0);
        minTime.set(Calendar.MINUTE, 0);
        minTime.set(Calendar.SECOND, 0);
        minTime.set(Calendar.MILLISECOND, 0);
        return minTime.getTime();
    }

    private Date getMaxTime(int year) {
        // 获取最大时间（年末）
        Calendar maxTime = Calendar.getInstance();
        maxTime.set(Calendar.YEAR, year);
        maxTime.set(Calendar.MONTH, 11);
        maxTime.set(Calendar.DAY_OF_MONTH, 31);
        maxTime.set(Calendar.HOUR_OF_DAY, 23);
        maxTime.set(Calendar.MINUTE, 59);
        maxTime.set(Calendar.SECOND, 59);
        maxTime.set(Calendar.MILLISECOND, 999);
        return maxTime.getTime();
    }

    public List<FailureRecord> pageList(Integer year) {
        QueryWrapper<FailureRecord> queryWrapper = new QueryWrapper<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        queryWrapper.between("failure_date", format.format(getMinTime(year)), format.format(getMaxTime(year)));
        return list(queryWrapper);
    }

    public List<FailureRecord> list(String startDateStr, String endDateStr) {
        //startDate:2024-01-10 00:00:00
        DateTime startDate = DateUtil.parse(startDateStr);
        DateTime endDate = DateUtil.parse(endDateStr);
        LambdaQueryChainWrapper<FailureRecord> wrapper = new LambdaQueryChainWrapper<>(dao);
        return wrapper.ge(StringUtils.isNotBlank(startDateStr), FailureRecord::getFailureDate, DateUtil.formatDate(startDate))
                .lt(StringUtils.isNotBlank(endDateStr), FailureRecord::getFailureDate, DateUtil.formatDate(endDate))
                .list();
    }
}
